/**
 * 描述：http
 */
import axios from 'axios';
import router from '@/router/';
import { Message } from 'element-ui';
import {Notice} from 'iview';

axios.defaults.timeout = 10000;
let isLoginTimeOut = true;

// 拦截
axios.interceptors.request.use(function (config) {
    // config.headers.TOKEN = 1;
  if (config.type && config.type === 'form-data') {
    config.headers['Content-Type'] = 'multipart/form-data';
  }
  if (config.type && config.type === 'url') {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
  }
  return config;
}, function (error) {
    console.log('error111111111111111111111111:' + error);
    Message.error({
        message: '加载超时'
    });
    return Promise.reject(error);
});

axios.interceptors.response.use(function (response) {
    if (response.data.result) {
        return Promise.resolve(response.data);
    } else {
        Message.error({message: response.data.message});
        return Promise.reject(response.data.message);
    }
}, (error) => {
  if (error && error.response) {
    let array = window.location.pathname.split('/');
    switch (error.response.status) {
      case 400:
        error.message = '请求错误';
        break;
      case 401:
        error.message = '未授权，请登录';
        if (isLoginTimeOut) Notice.open({desc: '登录信息已过期，请重新登录！'});
        if (array[1] === 'company') {
          router.replace({path: `/${array[1]}/login`});
        } else {
          router.replace({path: `/login`});
        }
        break;
      case 403:
        if (isLoginTimeOut) Notice.open({desc: '登录信息已过期，请重新登录！'});
        if (array[1] === 'company') {
          router.replace({path: `/${array[1]}/login`});
        } else {
          router.replace({path: `/login`});
        }
        error.message = '拒绝访问';
        break;
      case 404:
        error.message = '请求地址出错';
        break;
      case 408:
        error.message = '请求超时';
        break;
      case 500:
        error.message = '服务器内部错误';
        break;
      case 501:
        error.message = '服务未实现';
        break;
      case 502:
        error.message = '网关错误';
        break;
      case 503:
        error.message = '服务不可用';
        break;
      case 504:
        error.message = '网关超时';
        router.replace({path: `/home`});
        break;
      case 505:
        error.message = 'HTTP版本不受支持';
        break;
    }
    isLoginTimeOut = false;
    setTimeout(() => {
      isLoginTimeOut = true;
    }, 1000);
  }
  return Promise.reject(error);
});

export default axios;
